package com.gitee.cashzhang27.test.boot.functional.validator;

import com.gitee.cashzhang27.test.boot.functional.entity.Person;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * Person 校验类.
 *
 * @author Cash Zhang
 * @version v1.0 2020/09/15 16:14
 * @since v1.0
 */
@Component
public class PersonValidator implements Validator {

  /**
   * This Validator validates only Person instances.
   */
  @Override
  public boolean supports(@NonNull Class clazz) {
    return Person.class.equals(clazz);
  }

  @Override
  public void validate(@NonNull Object obj, @NonNull Errors e) {
    ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
    Person p = (Person) obj;
    if (p.getAge() < 0) {
      e.rejectValue("age", "negative value");
    } else if (p.getAge() > 110) {
      e.rejectValue("age", "too darn old");
    }
  }

}
